<template>
  <gc-dialog
    title="密码修改"
    :dialog-visible="true"
    @cancel="handleCancle"
    @ok="handleConfirm"
    width="400"
  >
    <el-form
      ref="formRef"
      label-position="top"
      :model="form"
      :rules="formRules"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          type="text"
          v-model="form.username"
          disabled
          placeholder="请输入" />
      </el-form-item>
      <el-form-item label="旧密码" prop="oldPassword" v-if="isSelf">
        <el-input
          type="password"
          v-model="form.oldPassword"
          show-password
          placeholder="请输入" />
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input
          type="password"
          v-model="form.password"
          show-password
          placeholder="请输入" />
      </el-form-item>
      <el-form-item label="确认密码" prop="validPassword">
        <el-input
          type="password"
          show-password
          v-model="form.validPassword"
          placeholder="请输入" />
      </el-form-item>
    </el-form>
  </gc-dialog>
</template>

<script setup lang="ts" name="ChangePassword">
import { ref, reactive } from 'vue'
import { ruleRequired, ruleMaxLength } from '@/utils/rules'
import type { FormInstance, FormRules } from 'element-plus'
import { apiChangeSelfPassword, apiChangePassword } from '@/http/service'
import { ElMessage } from 'element-plus'

const props = defineProps({
  username: String,
  isSelf: Boolean
})
const emit = defineEmits(['close-modal'])
const formRef = ref<null | FormInstance>(null)
const form = reactive({
  username: props.username,
  oldPassword: '',
  password: '',
  validPassword: ''
})
const formRules = reactive<FormRules>({
  username: [ruleRequired('请输入用户名'), ruleMaxLength(32)],
  oldPassword: [ruleRequired('请输入旧密码'), ruleMaxLength(32)],
  password: [ruleRequired('请输入密码'), ruleMaxLength(32)],
  validPassword: [ruleRequired('请输入确认密码'), ruleMaxLength(32), {
    validator: (_rule: any, value: any, callback: any) => {
      if (value !== form.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    },
    trigger: 'blur'
  }]
})

async function handleConfirm () {
  const valid = await formRef.value?.validate()
  if (valid) {
    const API = props.isSelf ? apiChangeSelfPassword : apiChangePassword
    await API({
      username: props.username,
      password: form.password,
      oldPassword: form.oldPassword
    })
    ElMessage.success('密码修改成功')
    emit('close-modal')
  }
}

function handleCancle () {
  emit('close-modal')
}
</script>

<style scoped lang="scss"></style>
